package com.ktjiaoyu.server.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //判断用户所拥有角色和权限是否和资源所需要的角色和权限匹配
        for (ConfigAttribute configAttribute : collection) {
            //获取资源所需要的角色
            String needRole = configAttribute.getAttribute();
            if(needRole.equals("ROLE_LOGIN")){//不受保护；只要登录就行
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("未登录");
                }else{
                    return;//放行
                }
            }else{//保护
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                for (GrantedAuthority authority : authorities) {
                    if(authority.getAuthority().equals(needRole)) {
                        //有权限可以正常访问
                        return;
                    }
                }
            }
        }
        //没有权限
        throw new AccessDeniedException("权限不足，请联系管理员!");
        //首先判断资源是不是受保护的
            //如果不受保护
                //判断是否登录
                     //登录了；放行
                    //没登录 ；抛出异常
            //如果受保护
                //判断资源所需要的角色和用户所拥有的角色是否一致
                    //如果一致 放行
                    //如果不一致 抛出异常
    }
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
